// Admin JavaScript for the Smart Attendance System

// Initialize Socket.IO connection
const socket = io();

// 全局函数声明 - 这些函数需要在全局作用域中可访问
window.deleteEmployee = deleteEmployee;
window.updateLeaveStatus = updateLeaveStatus;
window.deletePolicy = deletePolicy;
window.syncFaceRegistrationStatus = syncFaceRegistrationStatus;

// DOM Elements
const tabs = document.querySelectorAll('nav ul li a');
const tabContents = document.querySelectorAll('.tab-content');
const policyModal = document.getElementById('policy-modal');
const policyForm = document.getElementById('policy-form');
const employeeModal = document.getElementById('employee-modal');
const employeeForm = document.getElementById('employee-form');

// Tab navigation
function activateTab(tabName) {
    tabs.forEach(tab => {
        tab.classList.remove('active');
        if (tab.dataset.tab === tabName) {
            tab.classList.add('active');
        }
    });
    tabContents.forEach(content => {
        content.classList.remove('active');
        if (content.id === tabName) {
            content.classList.add('active');
        }
    });
}

// Socket.IO event listeners
socket.on('connect', () => {
    console.log('Connected to server');
});

socket.on('disconnect', () => {
    console.log('Disconnected from server');
});

// Real-time updates for dashboard
socket.on('update_dashboard', (data) => {
    document.getElementById('today-attendance').textContent = data.todayAttendance;
    document.getElementById('pending-leaves').textContent = data.pendingLeaves;
    document.getElementById('total-employees').textContent = data.totalEmployees;
    if (document.getElementById('month-late')) {
        document.getElementById('month-late').textContent = data.monthLate;
    }
});

// Modal handling
function openModal(modal) {
    modal.style.display = 'block';
}

function closeModal(modal) {
    modal.style.display = 'none';
}

// 删除员工
function deleteEmployee(employeeId) {
    if (!employeeId) {
        alert('员工ID无效，无法删除');
        return;
    }
    
    if (confirm(`确定要删除员工 ID: ${employeeId} 吗？此操作不可撤销。`)) {
        // 添加删除中的视觉反馈
        const row = document.getElementById(`employee-row-${employeeId}`);
        if (row) {
            row.style.backgroundColor = '#ffe0e0';
            row.style.opacity = '0.7';
        }
        
        fetch(`/api/employees/${employeeId}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(data => {
                    throw new Error(data.error || `删除失败，状态码: ${response.status}`);
                });
            }
            return response.json();
        })
        .then(data => {
            // 成功删除
            alert(data.message || '员工删除成功');
            
            // 更新员工列表
            loadEmployees();
            
            // 也更新仪表盘数据
            loadDashboardStats();
        })
        .catch(error => {
            console.error('删除员工失败:', error);
            
            // 恢复行的样式
            if (row) {
                row.style.backgroundColor = '';
                row.style.opacity = '';
            }
            
            alert(`删除员工失败: ${error.message}`);
        });
    }
}

// 更新请假状态
function updateLeaveStatus(requestId, status, comment = '') {
    fetch(`/api/leave-requests/${requestId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            status: status,
            admin_comment: comment
        })
    })
    .then(response => {
        if (response.ok) {
            alert('请假申请状态更新成功');
            loadLeaveRequests();
        } else {
            throw new Error('更新失败');
        }
    })
    .catch(error => {
        console.error('更新请假状态失败:', error);
        alert('更新请假状态失败');
    });
}

// 删除制度
function deletePolicy(policyId) {
    if (confirm('确定要删除该制度吗？')) {
        fetch(`/api/policies/${policyId}`, {
            method: 'DELETE'
        })
        .then(response => {
            if (response.ok) {
                alert('制度删除成功');
                loadPolicies();
            } else {
                throw new Error('删除失败');
            }
        })
        .catch(error => {
            console.error('删除制度失败:', error);
            alert('删除制度失败');
        });
    }
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    console.log('Admin interface initialized');
    
    // 初始化标签页切换
    initializeTabs();
    
    // 加载仪表盘数据
    loadDashboardStats();
    
    // 加载员工列表
    loadEmployees();
    
    // 加载考勤记录
    loadAttendanceRecords();
    
    // 加载请假申请
    loadLeaveRequests();
    
    // 加载制度列表
    loadPolicies();
    
    // 绑定事件
    bindEvents();
});

// 标签页切换功能
function initializeTabs() {
    const tabs = document.querySelectorAll('nav ul li a');
    tabs.forEach(tab => {
        tab.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('data-tab');
            
            // 移除所有活动状态
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            tabs.forEach(t => t.classList.remove('active'));
            
            // 激活目标标签页
            document.getElementById(targetId).classList.add('active');
            this.classList.add('active');
            
            console.log('Tab switched to:', targetId);
        });
    });
}

// 加载仪表盘统计数据
function loadDashboardStats() {
    fetch('/api/dashboard/stats')
        .then(response => response.json())
        .then(data => {
            // 更新统计数字
            document.getElementById('today-attendance').textContent = data.today_attendance;
            document.getElementById('pending-leaves').textContent = data.pending_leaves;
            document.getElementById('total-employees').textContent = data.total_employees;
        })
        .catch(error => {
            console.error('加载仪表盘数据失败:', error);
        });
}

// 加载员工列表
function loadEmployees() {
    const tbody = document.getElementById('employee-table-body');
    
    // 添加加载指示器
    tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 20px;">正在加载员工信息...</td></tr>';
    
    fetch('/api/employees')
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            return response.json();
        })
        .then(employees => {
            tbody.innerHTML = '';
            
            // 检查是否有员工数据
            if (!employees || !Array.isArray(employees) || employees.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 20px;">暂无员工信息</td></tr>';
                return;
            }
            
            // 遍历所有员工并创建表格行
            employees.forEach(employee => {
                if (!employee || !employee.employee_id) {
                    console.warn('发现无效的员工数据:', employee);
                    return; // 跳过无效数据
                }
                
                const row = document.createElement('tr');
                row.id = `employee-row-${employee.employee_id}`;
                
                // 使用安全的方式访问属性，防止undefined错误
                const employeeId = employee.employee_id || '';
                const name = employee.name || '未知';
                const department = employee.department || '-';
                const position = employee.position || '-';
                const faceRegistered = employee.face_registered ? '已注册' : '未注册';
                
                row.innerHTML = `
                    <td>${employeeId}</td>
                    <td>${name}</td>
                    <td>${department}</td>
                    <td>${position}</td>
                    <td>${faceRegistered}</td>
                    <td>
                        <button onclick="editEmployee('${employeeId}')" class="btn-edit">编辑</button>
                        <button onclick="deleteEmployee('${employeeId}')" class="btn-delete">删除</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
            
            console.log(`已加载 ${employees.length} 名员工的信息`);
        })
        .catch(error => {
            console.error('加载员工列表失败:', error);
            tbody.innerHTML = `<tr><td colspan="6" style="text-align: center; padding: 20px; color: red;">
                                加载员工信息失败: ${error.message}</td></tr>`;
        });
}

// 加载考勤记录
function loadAttendanceRecords() {
    const dateFrom = document.getElementById('attendance-date-from').value || new Date().toISOString().split('T')[0];
    const dateTo = document.getElementById('attendance-date-to').value || new Date().toISOString().split('T')[0];
    
    fetch(`/api/attendance?date_from=${dateFrom}&date_to=${dateTo}`)
        .then(response => response.json())
        .then(records => {
            const tbody = document.getElementById('attendance-table-body');
            tbody.innerHTML = '';
            
            records.forEach(record => {
                const row = document.createElement('tr');
                const date = new Date(record.check_in_time).toLocaleDateString();
                const checkInTime = new Date(record.check_in_time).toLocaleTimeString();
                const checkOutTime = record.check_out_time ? new Date(record.check_out_time).toLocaleTimeString() : '-';
                
                row.innerHTML = `
                    <td>${date}</td>
                    <td>${record.employee_id}</td>
                    <td>${record.name}</td>
                    <td>${checkInTime}</td>
                    <td>${checkOutTime}</td>
                    <td>${record.status}</td>
                `;
                tbody.appendChild(row);
            });
        })
        .catch(error => {
            console.error('加载考勤记录失败:', error);
        });
}

// 加载请假申请
function loadLeaveRequests() {
    const status = document.getElementById('leave-status-filter').value;
    
    fetch(`/api/leave-requests?status=${status}`)
        .then(response => response.json())
        .then(requests => {
            const tbody = document.getElementById('leave-table-body');
            tbody.innerHTML = '';
            
            requests.forEach(request => {
                const row = document.createElement('tr');
                const startDate = new Date(request.start_date).toLocaleDateString();
                const endDate = new Date(request.end_date).toLocaleDateString();
                
                let actionButtons = '';
                if (request.status === 'pending') {
                    actionButtons = `
                        <button onclick="updateLeaveStatus(${request.id}, 'approved')" class="btn-approve">批准</button>
                        <button onclick="updateLeaveStatus(${request.id}, 'rejected')" class="btn-reject">拒绝</button>
                    `;
                }
                
                row.innerHTML = `
                    <td>${request.id}</td>
                    <td>${request.employee_id}</td>
                    <td>${request.name}</td>
                    <td>${request.leave_type}</td>
                    <td>${startDate}</td>
                    <td>${endDate}</td>
                    <td>${request.reason}</td>
                    <td>${request.status}</td>
                    <td>${actionButtons}</td>
                `;
                tbody.appendChild(row);
            });
        })
        .catch(error => {
            console.error('加载请假申请失败:', error);
        });
}

// 加载制度列表
function loadPolicies() {
    fetch('/api/policies')
        .then(response => response.json())
        .then(policies => {
            const container = document.getElementById('policies-container');
            container.innerHTML = '';
            
            policies.forEach(policy => {
                const card = document.createElement('div');
                card.className = 'policy-card';
                // 截取content的前100个字符用于预览
                const contentPreview = policy.content && policy.content.length > 100 
                    ? policy.content.substring(0, 100) + '...' 
                    : policy.content || '';
                
                const dateString = policy.created_at 
                    ? new Date(policy.created_at).toLocaleDateString() 
                    : '未知日期';
                    
                card.innerHTML = `
                    <h3>${policy.title}</h3>
                    <p class="policy-category">${policy.category}</p>
                    <p class="policy-date">创建时间: ${dateString}</p>
                    <div class="policy-content-preview">${contentPreview}</div>
                    <div class="policy-actions">
                        <a href="/policy/${policy.id}" class="btn-view" target="_blank">查看</a>
                        <button onclick="deletePolicy(${policy.id})" class="btn-delete">删除</button>
                    </div>
                `;
                container.appendChild(card);
            });
        })
        .catch(error => {
            console.error('加载制度列表失败:', error);
        });
}

// 添加制度
function addPolicy(formData) {
    fetch('/api/policies', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => {
        if (response.ok) {
            alert('制度添加成功');
            loadPolicies();
        } else {
            throw new Error('添加失败');
        }
    })
    .catch(error => {
        console.error('添加制度失败:', error);
        alert('添加制度失败');
    });
}

// 添加员工
function addEmployee(formData) {
    fetch('/api/employees', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(data => {
                throw new Error(data.error || `添加失败，状态码: ${response.status}`);
            });
        }
        return response.json();
    })
    .then(data => {
        alert('员工添加成功');
        loadEmployees();
        loadDashboardStats();
    })
    .catch(error => {
        console.error('添加员工失败:', error);
        alert(`添加员工失败: ${error.message}`);
    });
}

// 编辑员工
function editEmployee(employeeId) {
    // 根据ID获取员工信息
    fetch(`/api/employees/${employeeId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取员工信息失败');
            }
            return response.json();
        })
        .then(employee => {
            // 填充表单
            document.getElementById('employee-modal-title').textContent = '编辑员工';
            document.getElementById('employee-id').value = employee.employee_id || '';
            document.getElementById('employee-id').readOnly = true; // 不允许修改员工ID
            document.getElementById('employee-name').value = employee.name || '';
            document.getElementById('employee-department').value = employee.department || '';
            document.getElementById('employee-position').value = employee.position || '';
            
            // 显示人脸注册状态（只读）
            const faceStatusEl = document.getElementById('face-status-display');
            faceStatusEl.textContent = employee.face_registered ? '已注册' : '未注册';
            faceStatusEl.className = employee.face_registered ? 'status-registered' : 'status-not-registered';
            
            // 设置表单提交动作为更新
            employeeForm.dataset.mode = 'edit';
            employeeForm.dataset.employeeId = employeeId;
            
            // 显示模态框
            openModal(employeeModal);
        })
        .catch(error => {
            console.error('获取员工信息失败:', error);
            alert('获取员工信息失败');
        });
}

// 更新员工
function updateEmployee(employeeId, formData) {
    fetch(`/api/employees/${employeeId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(data => {
                throw new Error(data.error || `更新失败，状态码: ${response.status}`);
            });
        }
        return response.json();
    })
    .then(data => {
        alert('员工信息更新成功');
        loadEmployees();
    })
    .catch(error => {
        console.error('更新员工失败:', error);
        alert(`更新员工失败: ${error.message}`);
    });
}

// 绑定事件
function bindEvents() {
    // 筛选考勤记录
    document.getElementById('filter-attendance-btn').addEventListener('click', loadAttendanceRecords);
    
    // 筛选请假申请
    document.getElementById('filter-leave-btn').addEventListener('click', loadLeaveRequests);
    
    // 添加制度
    document.getElementById('add-policy-btn').addEventListener('click', function() {
        document.getElementById('policy-modal').style.display = 'block';
    });
    
    // 添加员工
    document.getElementById('add-employee-btn').addEventListener('click', function() {
        // 重置表单
        document.getElementById('employee-modal-title').textContent = '添加员工';
        document.getElementById('employee-id').value = '';
        document.getElementById('employee-id').readOnly = false; // 新增时允许输入员工ID
        document.getElementById('employee-name').value = '';
        document.getElementById('employee-department').value = '';
        document.getElementById('employee-position').value = '';
        
        // 新员工默认未注册人脸
        const faceStatusEl = document.getElementById('face-status-display');
        faceStatusEl.textContent = '未注册';
        faceStatusEl.className = 'status-not-registered';
        
        // 设置表单提交动作为添加
        employeeForm.dataset.mode = 'add';
        
        // 显示模态框
        openModal(employeeModal);
    });
    
    // 同步人脸状态
    document.getElementById('sync-face-status-btn').addEventListener('click', function() {
        syncFaceRegistrationStatus();
    });
    
    // 关闭模态框
    document.querySelectorAll('.close, .close-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal').style.display = 'none';
        });
    });
    
    // 提交制度表单
    document.getElementById('policy-form').addEventListener('submit', function(e) {
        e.preventDefault();
        const formData = {
            title: document.getElementById('policy-title').value,
            category: document.getElementById('policy-category').value,
            content: document.getElementById('policy-content').value
        };
        addPolicy(formData);
        this.closest('.modal').style.display = 'none';
    });
    
    // 提交员工表单
    document.getElementById('employee-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = {
            employee_id: document.getElementById('employee-id').value,
            name: document.getElementById('employee-name').value,
            department: document.getElementById('employee-department').value,
            position: document.getElementById('employee-position').value
            // 不再从表单中提交face_registered，该字段由后端根据face_encoding自动管理
        };
        
        if (this.dataset.mode === 'edit') {
            updateEmployee(this.dataset.employeeId, formData);
        } else {
            addEmployee(formData);
        }
        
        this.closest('.modal').style.display = 'none';
    });
}

// 同步人脸注册状态
function syncFaceRegistrationStatus() {
    if (confirm('确定要同步所有员工的人脸注册状态吗？这将根据员工是否有人脸数据来更新注册状态。')) {
        fetch('/api/employees/sync-face-status', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(data => {
                    throw new Error(data.error || `同步失败，状态码: ${response.status}`);
                });
            }
            return response.json();
        })
        .then(data => {
            alert(`同步成功! ${data.message}`);
            
            // 如果返回了统计信息，显示详细信息
            if (data.stats) {
                const { registered, not_registered, total } = data.stats;
                console.log(`同步完成: ${registered}人已注册, ${not_registered}人未注册, 共${total}人`);
            }
            
            // 刷新员工列表
            loadEmployees();
        })
        .catch(error => {
            console.error('同步人脸注册状态失败:', error);
            alert(`同步失败: ${error.message}`);
        });
    }
}

// 全局暴露函数
window.editEmployee = editEmployee;